package hoowin.app.wsnd.dao.springImp;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import hoowin.app.wsnd.dao.IStatusDao;
import hoowin.app.wsnd.model.Status;
import hoowin.basic.util.Trans;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class StatusDao extends JdbcDaoSupport implements IStatusDao {

	@Override
	public Status getStatusById(int id) {
		String sql = "select * from apps_wsnd_status where id="+id;
		return (Status)super.getJdbcTemplate().queryForObject(sql, new StatusRowMapper());
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public List getStatusListByPublisherId(int publisherId) {
		String sql = "select * from apps_wsnd_status where publisher="+publisherId;
		return super.getJdbcTemplate().query(sql, new StatusRowMapper());
	}

	@Override
	public int addStatus(Status status) {
		String sql = "insert into apps_wsnd_status (id, publisher, language, publish_time, content) values (null, ?, ?, ?, ?)";
		if(super.getJdbcTemplate().update(sql,status.getPublisherId(), status.getLanguage(), Trans.dateToString(new Date()), status.getContent() )>0){
			return super.getJdbcTemplate().queryForInt("select last_insert_id()");
		}else return 0;
	}

	@Override
	public boolean deleteStatusById(int id) {
		if(super.getJdbcTemplate().update("delete from apps_wsnd_status where id="+id)>0)return true;
		return false;
	}

	@Override
	public boolean deletestatusByPublisherId(int publisherId) {
		if(super.getJdbcTemplate().update("delete from apps_wsnd_status where publisher="+publisherId)>0)return true;
		return false;
	}
	
	class StatusRowMapper implements RowMapper<Object>{
		@Override
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			Status status = new Status();
			status.setId(rs.getInt("id"));
			status.setPublisherId(rs.getInt("publisher"));
			status.setLanguage(rs.getString("language"));
			status.setPublishTime(Trans.stringToDate(rs.getString("publish_time")));
			status.setContent(rs.getString("content"));
			return status;
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public List getStatusOfFollowees(int userId) {
		String sql = "select * from apps_wsnd_status where publisher in (select followee_id from basic_user_follows where follower_id="+userId+")";
		return super.getJdbcTemplate().query(sql, new StatusRowMapper());
	}
}
